# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'hnzbkj01': {
        'API_KEY': '8b2de685acc4efsmth3f147eaded49bd',
        'gateway': 'http://117.50.15.62:9911/code/reqPayOtherWY?cpid={}&cpparam={}&fee={}&ip={}&goodsname={}&app={}',
        'query_gateway': 'http://117.50.15.62:9911/code/getPayOtherResult',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# cpid,cpparam,fee,ffid
def generate_notify_sign(d, key):
    s = 'cpid={}&cpparam={}&fee={}&ffid={}&key={}'.format(d['cpid'], d['cpparam'], d['fee'], d['ffid'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xun1pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型.支付宝：01，微信：02，快捷：03，QQ钱包：04
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '02'
    elif service == 'alipay':
        payType = '01'
    elif service == 'qq':
        payType = '04'
    else:
        payType = '03'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    d = OrderedDict((
        ('cpid', mch_id),
        ('fee', str(int(pay_amount * 100))),
        ('ip', _get_device_ip(info)),
        ('playerid', str(pay.user_id)),
        ('cpparam', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/xun1pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('app', 'charge'),
        ('goodsname', 'charge'),
    ))
    url = _get_gateway(mch_id).format(d['cpid'], d['cpparam'], d['fee'], d['ip'], d['goodsname'], d['app'])
    _LOGGER.info("xun1pay create data: %s", url)
    response = requests.get(url)
    _LOGGER.info("xun1pay create rsp: %s", response.text)
    j = json.loads(response.text)
    order_db.fill_third_id(pay.id, j['orderid'])
    return {'charge_info': j['url']}


# ok
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("xun1pay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['cpparam']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('xun1pay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['ffid']
    total_fee = float(data['fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1为成功，6为退款，其他为失败
    if trade_status == 1:
        _LOGGER.info('xun1pay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    p_dict = {
        'cpid': app_id,
        'orderid': str(pay_order.third_id),
    }
    _LOGGER.info(u'xun1pay query data: %s', p_dict)
    response = requests.get(_get_query_gateway(app_id), data=p_dict, )
    _LOGGER.info(u'xun1pay query: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['result'])  # 0 订单未成功 1订单成功
        total_fee = float(data['fee']) / 100.0
        trade_no = data['orderid']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('xun1pay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('xun1pay data error, status_code: %s', response.status_code)
